package com.hhf.feiojjudgeservice.codesandbox.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.hhf.feiojcommonservice.common.ErrorCode;
import com.hhf.feiojcommonservice.exception.BusinessException;
import com.hhf.feiojjudgeservice.codesandbox.CodeSandbox;
import com.hhf.feiojjudgeservice.codesandbox.model.ExecuteCodeRequest;
import com.hhf.feiojjudgeservice.codesandbox.model.ExecuteCodeResponse;
import org.springframework.beans.factory.annotation.Value;

/**
 * @Author hhf
 * @Date 2024/10/27
 * @Description 远程调用代码沙箱
 */
public class RemoteCodeSandbox implements CodeSandbox {

    @Value(value = "${codesandbox.port:8080}")
    private static Integer port;

    @Value(value = "${codesandbox.host:localhost}")
    private static String host;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

        String url = host + StrUtil.C_COLON + port;

        String method = "/execute/code";

        String bodyStr = JSONUtil.toJsonStr(executeCodeRequest);


        String resultStr = HttpUtil.createPost(url + method)
                .body(bodyStr)
                .execute()
                .body();

        if (StrUtil.isBlank(resultStr)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "executeCode remoteSandbox error, message = " + resultStr);
        }

        return JSONUtil.toBean(resultStr, ExecuteCodeResponse.class);

    }
}

